#include "stm32f10x.h"
#include "i2c.h"
#include "lcd.h"
#include "key.h"
#include "pwm.h"
#include "adc.h"
#include "stdio.h"

u32 TimingDelay = 0;
float adc_val = 1.0;
extern u8 lcd_state;
extern u8 fre;

//Main Body
int main(void)
{
	char text[20];
	SysTick_Config(SystemCoreClock/1000);
	STM3210B_LCD_Init();
  LCD_SetTextColor(White);
  LCD_SetBackColor(Blue2);
  LCD_Clear(Blue2);
	led_init();
	i2c_init();
	pwm_init();
	adc_init();
	key_init();
	fre = read_data(1);
	
	while(1)
	{
		adc_val = get_adc();
		state_get();
		write_data(1,fre);
		delay_ms(5);
		switch(lcd_state){
			case state_pause:{
				sprintf(text,"    Parma Window        ");
				LCD_DisplayStringLine(Line2,text);
				sprintf(text,"Voltage:%.2lfV   ",adc_val);
				LCD_DisplayStringLine(Line3,text);
				sprintf(text,"OutState:OFF");
				LCD_DisplayStringLine(Line4,text);
				sprintf(text,"SignalPar:");
				LCD_DisplayStringLine(Line5,text);
				sprintf(text,"           PA9: %2d%%",(int)((adc_val*100)/3.3));
				LCD_DisplayStringLine(Line6,text);
				sprintf(text,"           PA14:%2d%%",100-(int)((adc_val*100)/3.3));
				LCD_DisplayStringLine(Line7,text);
				sprintf(text,"           %dKHz   ",fre);
				LCD_DisplayStringLine(Line8,text);
			}break;
			case state_running:{
				sprintf(text,"    Parma Window       ");
				LCD_DisplayStringLine(Line2,text);
				sprintf(text,"Voltage:%.2lfV   ",adc_val);
				LCD_DisplayStringLine(Line3,text);
				sprintf(text,"OutState:ON  ");
				LCD_DisplayStringLine(Line4,text);
				sprintf(text,"SignalPar:");
				LCD_DisplayStringLine(Line5,text);
				sprintf(text,"           PA9: %2d%%",(int)((adc_val*100)/3.3));
				LCD_DisplayStringLine(Line6,text);
				sprintf(text,"           PA14:%2d%%",100-(int)((adc_val*100)/3.3));
				LCD_DisplayStringLine(Line7,text);
				sprintf(text,"           %dKHz   ",fre);
				LCD_DisplayStringLine(Line8,text);
				TIM_SetCompare2(TIM1,(int)((adc_val/3.3)*1000/fre)-1);
			}break;
			case state_setting:{
				LCD_ClearLine(Line3);
				LCD_ClearLine(Line4);
				LCD_ClearLine(Line6);
				LCD_ClearLine(Line7);
				LCD_ClearLine(Line8);
				sprintf(text,"   Setting Window     ");
				LCD_DisplayStringLine(Line2,text);
				sprintf(text,"Frequency:%dKHz           ",fre);
				LCD_DisplayStringLine(Line5,text);
			}break;
		}
	}
}

//